<template>
  <v-container fluid class="fill-height">
    <v-row>
      <v-col cols="12" xs="12" sm="6" md="5" lg="4" class="ma-auto">
        <v-card outlined :loading="loading">
          <div class="px-8 pt-6 pb-12">
            <v-card-title class="text-center">EchoVivid</v-card-title>
            <v-card-subtitle class="mb-5">登录</v-card-subtitle>
            <v-card-text>
              <ValidationObserver ref="form" v-slot="{ reset, handleSubmit }">
                <form @submit.prevent="handleSubmit(login)" @reset.prevent="reset">
                  <ValidationProvider v-slot="{ errors }" name="邮箱" rules="required|email">
                    <v-text-field v-model="email" :error-messages="errors" label="邮箱" outlined></v-text-field>
                  </ValidationProvider>
                  <ValidationProvider v-slot="{ errors }" name="密码" rules="required|min:6">
                    <p class="ma-0 text-right">
                      <v-btn text small class="pl-0 text-capitalize" color="primary" href="/resetpwd">找回密码?</v-btn>
                    </p>
                    <v-text-field v-model="password" type="password" :error-messages="errors" label="密码"
                      outlined></v-text-field>
                  </ValidationProvider>
                  <div class="mt-6 d-flex justify-space-between">
                    <v-btn text small class="pl-0 text-capitalize" color="primary" router to="signup">注册</v-btn>
                    <v-btn type="submit" class="primary" :loading="loading" depressed>登录</v-btn>
                  </div>
                </form>
              </ValidationObserver>
            </v-card-text>
          </div>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
//import { getCurrentUser, login } from '../../services/UserRequest';

export default {
  name: 'login',
  data: () => ({
    email: '',
    password: '',
    loading: false
  }),
  methods: {
    async login() {
      console.log("登录..")
      if (this.loading) return
      this.loading = true
      const data = await this.$store
        .dispatch('login', { email: this.email, password: this.password })
        .catch((err) => {
          this.loading = false
          console.log(err)
          this.$refs.form.setErrors({
            '邮箱': ["邮箱或密码错误"],
            '密码': ["邮箱或密码错误"],
          })
          return
        })
      if (!data) return
      if (data.code == 500) {
        console.log(data.code)
        this.$refs.form.setErrors({
          '邮箱': ["邮箱或密码错误"],
          '密码': ["邮箱或密码错误"],
        })
        this.loading = false
        return
      }
      const user = await this.$store
        .dispatch('getCurrentUser')
        .catch((err) => console.log(err))

      if (!user) return
      this.loading = false
      this.$router.push({ name: 'Home' }).then(() => {
        console.log('跳转成功了')
        window.location.reload();
      });
    }
  }
}
</script>

<style></style>
